<template>
  <div class="content-wrapper-1">
    <loginOut :pageName="t('materialOutbound.pageTitle')" />
    <div class="content">
      <!-- 序列号输入区域 -->
      <div class="serial-input-wrapper">
        <div class="serial-input-container">
         
          <el-input
            v-model="serial"
            class="serial-input"
            :placeholder="t('materialOutbound.inputPlaceholder')"
            clearable
            @keyup.enter="handleSerialInput"
            ref="inputRef"
          >
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 序列号信息列表 -->
      <div class="serial-list-container">
       
        <el-table
          v-loading="loading"
          :data="list"
          border
          height="500"
       
          :empty-text="t('materialOutbound.emptyText')"
        >
          <el-table-column prop="serialNo" :label="t('materialOutbound.table.serialNo')" align="center" min-width="180" />
          <el-table-column prop="itemCode" :label="t('materialOutbound.table.itemCode')" align="center" min-width="120" />
          <el-table-column prop="diskNo" :label="t('materialOutbound.table.diskNo')" align="center" min-width="100" />
          <el-table-column :label="t('materialOutbound.table.qty')" align="center" min-width="120">
            <template #default="scope"> {{ scope.row.qty }}{{ scope.row.unit }} </template>
          </el-table-column>
          <el-table-column prop="storageLocation" :label="t('materialOutbound.table.storageLocation')" align="center" min-width="120" />
          <el-table-column
            prop="receiveDate"
            :label="t('materialOutbound.table.outboundDate')"
            align="center"
            min-width="140"
            :formatter="formatDate"
          />
          <el-table-column prop="receiver" :label="t('materialOutbound.table.outboundPerson')" align="center" min-width="100" />
          <el-table-column :label="t('materialOutbound.table.actions')"  align="center" min-width="120">
            <template #default="scope">
              <!-- 只有通过对话框添加的记录才显示打印条码按钮 -->
              <!--            <el-button-->
              <!--              v-if="!scope.row.isScanned"-->
              <!--              size="small"-->
              <!--              type="text"-->
              <!--              @click="printCode(scope.row)"-->
              <!--              danger-->
              <!--            >-->
              <!--              打印条码-->
              <!--            </el-button>-->
              <el-button size="small" type="text" @click="handleDelete(scope.row)" danger>
                 {{ t('materialOutbound.buttons.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 底部按钮区域 -->
      <div class="button-container-b">
        <el-button type="success" @click="saveData"> {{ t('materialOutbound.buttons.save') }} </el-button>
        <el-button @click="cancelOperation"> {{ t('materialOutbound.buttons.cancel') }}  </el-button>
      </div>

      <!-- 添加记录对话框 -->
      <!--    <el-dialog-->
      <!--      v-model="addDialogVisible"-->
      <!--      title="添加记录"-->
      <!--      width="40%"-->
      <!--      :close-on-click-modal="false"-->
      <!--    >-->
      <!--      <el-form-->
      <!--        :model="addForm"-->
      <!--        :rules="addFormRules"-->
      <!--        ref="addFormRef"-->
      <!--        label-width="100px"-->
      <!--      >-->
      <!--        <el-form-item label="品号" prop="itemCode">-->
      <!--          <el-input v-model="addForm.itemCode" clearable/>-->
      <!--        </el-form-item>-->
      <!--        <el-form-item label="数量" prop="quantity">-->
      <!--          <el-input v-model.number="addForm.quantity" type="number" clearable/>-->
      <!--        </el-form-item>-->
      <!--        <el-form-item label="单位" prop="unit">-->
      <!--          <el-input v-model="addForm.unit" clearable/>-->
      <!--        </el-form-item>-->
      <!--        <el-form-item label="入库位置" prop="storageLocation">-->
      <!--          <el-input v-model="addForm.storageLocation" clearable/>-->
      <!--        </el-form-item>-->
      <!--      </el-form>-->
      <!--      <template #footer>-->
      <!--        <el-button @click="addDialogVisible = false">取消</el-button>-->
      <!--        <el-button type="primary" @click="handleAddRecord">确定</el-button>-->
      <!--      </template>-->
      <!--    </el-dialog>-->
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref, nextTick, defineOptions } from 'vue'
import { MaterialInventorApi } from '@/api/opticore/materialinventor'
import loginOut from '@/components/loginOut/index.vue'

/** 报工记录 列表 */
defineOptions({ name: 'WorkReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 状态管理
const loading = ref(false) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const serial = ref('') // 物料序列号
const inputRef = ref() // 输入框引用

// 报工表单
const form = ref({
  operator: JSON.parse(localStorage.getItem('userInfo') || '{}').nickname || '' // 默认值
})

/** 处理序列号输入（扫描添加） */
const handleSerialInput = async () => {
  const inputValue = serial.value.trim()
  if (!inputValue) {
    message.warning(t('materialOutbound.messages.enterSerial'))
    return
  }

  // 检查序列号唯一性
  if (list.value.some((item) => item.serialNo === inputValue)) {
    message.warning(t('materialOutbound.messages.serialAlreadyInList'))
    return
  }

  // 显示加载状态
  loading.value = true

  try {
    // 如果在MaterialUsageApi中找不到，尝试从MaterialInventorApi获取
    const stockItem = await MaterialInventorApi.getMaterialInventorBySerialNo(inputValue)
    if (!stockItem) {
      message.warning(t('materialOutbound.messages.itemNotFound'))
      loading.value = false
      return
    }

    // 构建新记录，添加isScanned标记为true（表示是扫描添加）
    const newRecord = {
      id: stockItem.id, // 生成唯一ID
      serialNo: stockItem.serialNo, // 完整序列号
      itemCode: stockItem.itemCode, // 品号
      qty: stockItem.qty, // 数量
      unit: stockItem.unit || '', // 单位
      diskNo: stockItem.fiberPalletNo || '', // 纤盘号
      storageLocation: stockItem.location || '', // 入库位置
      receiveDate: new Date().toISOString(), // 当前时间
      receiver: form.value.operator, // 领用人
      materialType: stockItem.materialType || '',
      isScanned: true // 标记为扫描添加的记录
    }

    // 添加到列表
    list.value = [...list.value, newRecord]
    message.success(t('materialOutbound.messages.addSuccess'))
  } catch (error) {
    console.error('获取物料信息失败:', error)
    message.error(t('materialOutbound.messages.fetchFailed'))
  } finally {
    // 清空输入框
    serial.value = ''

    // 关闭加载状态
    loading.value = false

    // 聚焦输入框
    nextTick(() => {
      inputRef.value?.focus()
    })
  }
}

/** 保存数据 */
const saveData = async () => {
  if (list.value.length === 0) {
    message.warning(t('materialOutbound.messages.listEmpty'))
    return
  }

  try {
    // 显示加载状态
    loading.value = true

    // 准备出库数据，确保qty和unit字段正确分离
    const outboundData = list.value.map((item) => ({
      ...item,
      // 确保qty是数字类型
      qty: typeof item.qty === 'number' ? item.qty : Number(item.qty) || 0,
      // 确保unit是字符串类型
      unit: item.unit || ''
    }))

    // 调用中间库出库API
    await MaterialInventorApi.outboundMaterialInventor(outboundData)

    // 保存成功后清空列表
    list.value = []
    message.success(t('materialOutbound.messages.saveSuccess'))
  } catch (error) {
    console.error('保存出库数据失败:', error)
    message.error(t('materialOutbound.messages.saveFailed'))
  } finally {
    // 关闭加载状态
    loading.value = false
  }
}

/** 取消操作 */
const cancelOperation = () => {
  // 询问用户是否确认取消
  ElMessageBox.confirm( t('materialOutbound.messages.cancelConfirm'), 
    t('materialOutbound.messages.prompt'), {
    confirmButtonText: t('materialOutbound.buttons.confirm'),
      cancelButtonText: t('materialOutbound.buttons.cancel'),
    type: 'warning'
  })
    .then(() => {
      // 清空列表
      list.value = []
      message.info(t('materialOutbound.messages.listCleared'))
    })
    .catch(() => {
      // 用户取消了操作
      message.info(t('materialOutbound.messages.operationCancelled'))
    })
}

/** 格式化日期显示 */
const formatDate = (row: any, column: any) => {
  if (!row.receiveDate) return '-'
  return new Date(row.receiveDate).toLocaleString()
}

/** 处理删除操作 */
const handleDelete = (row: any) => {
  // 过滤掉要删除的记录
  list.value = list.value.filter((item) => item.id !== row.id)
  message.success(t('materialOutbound.messages.deleteSuccess'))
}

/** 初始化 **/
onMounted(() => {
  // 聚焦输入框
  nextTick(() => {
    inputRef.value?.focus()
  })
})
</script>

<style scoped lang="less">
.content-wrapper-1 {
 height: 100vh;
    padding: 0 16px;
    margin-top: 70px;
    background-color: #e7edf6;
}
.work-report-container {
  padding: 40px 20px;
  min-height: 100vh;
}

.serial-input-wrapper {
  margin-bottom: 16px;

  padding: 20px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
}

.serial-input-container {
  display: flex;
  align-items:center;
  width: 50%;
  max-width: 600px;
}

.serial-input {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.serial-list-container {
  padding: 16px;
  margin-top: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background-color: #fff;
  /* overflow: hidden; */
  .t {
    margin-bottom: 16px;
    font-size: 16px;
    color: #515a6e;
    font-weight: 600;
  }
}

.button-container-b {
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 10px;
  width: 100vw;
  z-index: 999;
  background-color: #fff;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

::v-deep .el-table tr:hover > td {
  background-color: #f9fafb !important;
}

::v-deep .el-table--border th,
::v-deep .el-table--border td {
  border-right: 1px solid #e5e7eb;
}

::v-deep .el-table--border {
  border-left: 1px solid #e5e7eb;
}
</style>
